<?php

namespace beepay;

use beepay\util\BeepayKit;
use InvalidArgumentException;

class Group
{
    const VERSION = '1.0';
    const DEFAULT_SIGN_TYPE = 'MD5';
    const API_VERSION_NAME = 'version';
    const API_SIGN_TYPE_NAME = 'signType';
    const API_SIGN_NAME = 'sign';
    const API_REQ_TIME_NAME = 'reqTime';

    protected $name;
    protected $client;

    public function __construct(BeepayClient $client, $name = null)
    {
        $this->name = $name;
        $this->client = $client;
    }

    public function request($method, $uri = '', $options = [])
    {
        if ($this->name) {
            $uri = $this->name . '/' . $uri;
        }
        $options['form_params'] = $this->buildBeepaySignature($options['form_params']);
        return $this->client->request($method, $uri, $options);
    }

    protected function getRequestClass($method)
    {
        $className = ucfirst($method);
        if ($this->name) {
            $className = $this->name . "\\" . $className;
        }

        return "\\beepay\\request\\" . $className;
    }

    public function __call($method, $params)
    {

        $reqClass = $this->getRequestClass($method);

        if (class_exists($reqClass)) {
            return new $reqClass($this, ...$params);
        }

        throw new InvalidArgumentException("Api {$method} not found!");
    }

    private function buildBeepaySignature($params)
    {
        $params += [
            self::API_VERSION_NAME => '1.0',
            self::API_SIGN_TYPE_NAME => self::DEFAULT_SIGN_TYPE,
            self::API_REQ_TIME_NAME => time()
        ];
        $apiKey = $this->client->getApiKey();
        $params[self::API_SIGN_NAME] = BeepayKit::getSign($params, $apiKey);
        return $params;
    }
}
